package cn.com.flever.utils;

import com.google.common.base.CaseFormat;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.*;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

public class MapperUtil {


    /**
     * 合并mapper文件
     * @param sourceMapper 源mapper文件
     * @param currentMapper 当前生成的mapper文件
     * @return
     */
    public static File MergeMapperXml(File sourceMapper,File currentMapper) {
        try {
            //读取新的mapper
            SAXReader reader = new SAXReader();
            Document sourceDocument = reader.read(new BufferedInputStream(new FileInputStream(sourceMapper)));
            Document currentDocument = reader.read(new BufferedInputStream(new FileInputStream(currentMapper)));
            String encode= sourceDocument.getXMLEncoding();
            //读取新mapper中的所有具有id属性的子元素
            Element root=currentDocument.getRootElement();
            Element sourceRoot=sourceDocument.getRootElement();
            List<Node> elements = root.selectNodes("//*[@id]");
            for (Node item : elements) {
                //根据id在旧的mapper中寻找到该element
                String id=item.valueOf("@id");
                Node node = sourceDocument.selectSingleNode("//*[@id='" + id + "']");
                if(node!=null)
                {
                    //替换节点
                    List content = node.getParent().content();
                    content.set(content.indexOf(node),item);
                }
                else
                {
                    item.setParent(null);
                    sourceRoot.add(item);
                }

            }
            sourceRoot.setDocument(null);
            sourceDocument.setRootElement(sourceRoot);
            //替换原本mapper文件
            OutputFormat format = OutputFormat.createPrettyPrint();
            //6.//创建一个xml文件
            OutputStream out = new FileOutputStream(currentMapper);
            Writer wr = new OutputStreamWriter(out, encode);//用可改变编码的OutputStreamWriter代替了普通的FileWriter解决中文乱码问题
            XMLWriter output = new XMLWriter(wr,format);
            //7.将doc输出到xml文件中
            output.write(sourceDocument);
            //8.关闭资源
            wr.close();
            out.close();
            output.close();
            return sourceMapper;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



    public static void main(String[] args) {
        MergeMapperXml(new File("E:\\AwardMessageRecordGenMapper.xml"),new File("E:\\ActivityGenMapper.xml"));
    }

}
